﻿/*

Copyright (c) 2009, Stephen Remde
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY STEPHEN REMDE ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHEN REMDE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace ConceptLink
{
    /// <summary>
    /// Static class to get the Links In and Out of a concept, and potentially cache them
    /// </summary>
    public class Links : JSPTask
    {
        /// <summary>
        /// class to store extra information about the link if needed
        /// </summary>
        public class LinksResult : Article
        {
        }


        public delegate void SearchResultsCallback(int id, LinksResult[] outlinks, LinksResult[] inlinks);


        /// <summary>
        /// Gets the links to and/or from an article
        /// </summary>
        /// <param name="id">ID of the article we want links to or from</param>
        /// <param name="ins">return in in links</param>
        /// <param name="outs">return out links</param>
        /// <param name="id2">ID of the article to find relatedness of links to. If set to -1 only the relateness to the first article is returned.</param>
        /// <param name="callback">Function to call with the results</param>
        public static void Get(int id, bool ins, bool outs, int id2, SearchResultsCallback callback)
        {
            Article dest = Search.Get(id2);

            GetXml((id2 != -1 && astaravailable) ? string.Format(astarurl, id, id2) : string.Format(linkurl, id),
                    delegate(XDocument x)
                    {
                        if (x == null)
                        {
                            callback(id, null, null);
                            return;
                        }

                        List<LinksResult> insresults = new List<LinksResult>();
                        List<LinksResult> outresults = new List<LinksResult>();

                        string articlename = 
                            x.Element("WikipediaMinerResponse")
                            .Element("SearchResponse")
                            .Element("Article")
                            .Attribute("title").Value;

                        foreach (var node in x.Descendants("SharedLink"))
                        {
                            LinksResult entry = new LinksResult()
                            {                                   
                                id    = int.Parse(node.Attribute("id").Value),
                                title = node.Attribute("title").Value                                 
                            };

                            outresults.Add(entry);
                            insresults.Add(entry);                            

                            if ((id2 != -1 && astaravailable) && dest != null)
                                Relatedness.Add(dest.title,
                                    node.Attribute("title").Value,
                                    float.Parse(node.Attribute("relatednessdest").Value));

                            Relatedness.Add(articlename, node.Attribute("title").Value, 
                                float.Parse(node.Attribute("relatedness").Value));
                        }

                        foreach (var node in x.Descendants("LinkOut"))
                        {
                            LinksResult entry = new LinksResult()
                            {
                                id = int.Parse(node.Attribute("id").Value),
                                title = node.Attribute("title").Value
                            };

                            outresults.Add(entry);

                            if ((id2 != -1 && astaravailable) && dest != null)
                                Relatedness.Add(dest.title,
                                    node.Attribute("title").Value,
                                    float.Parse(node.Attribute("relatednessdest").Value));

                            Relatedness.Add(articlename, node.Attribute("title").Value,
                                float.Parse(node.Attribute("relatedness").Value));
                        }

                        foreach (var node in x.Descendants("LinkIn"))
                        {
                            LinksResult entry = new LinksResult()
                            {
                                id = int.Parse(node.Attribute("id").Value),
                                title = node.Attribute("title").Value
                            };

                            insresults.Add(entry);

                            if ((id2 != -1 && astaravailable) && dest != null)
                                Relatedness.Add(dest.title,
                                    node.Attribute("title").Value,
                                    float.Parse(node.Attribute("relatednessdest").Value));

                            Relatedness.Add(articlename, node.Attribute("title").Value,
                                float.Parse(node.Attribute("relatedness").Value));
                        }


                        callback(id, outresults.ToArray(), insresults.ToArray());

                    });
        }
    }
}
